package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {
	
	private static ExecutorService workerPool;
	private static ServerSocket providerSocket;
	private Socket connection = null;
	
    public WorkerThread(Socket accept) throws SocketException {
    	this.connection = accept;
    	connection.setSoTimeout( Parameter.getTimeout() );
	}

	public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        
        workerPool = Executors.newFixedThreadPool(workers);
        providerSocket = new ServerSocket(port);
        while (true){
        	workerPool.execute( new WorkerThread(providerSocket.accept()) );
        }
    }

    public void run() {
    	
    	try {
			(new Worker()).handleRequest(this.connection);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}